package pl.jad.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Logger;

/**
 * Uzyskiwanie polaczenia z baza danych na podstawie okreslonej konfiguracji
 *
 */
final public class DbManager {
	private static boolean _hasDriverInstance;
	
	private static DbConfig _config;
	
	private static Connection _connection;
	
	private static final Logger _Log = Logger.getLogger("pl.jad.database.DbManager");
	
	/**
	 * Constructor
	 */
	protected DbManager() {
	}
	
	/**
	 * Returns name of the schema we use
	 * @return
	 */
	public static String getSchema() {
		return _config.getSchema();
	}
	
	/**
	 * Initializes driver instance
	 * 
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws ClassNotFoundException
	 */
	private static void getDriverInstance() throws InstantiationException, IllegalAccessException, ClassNotFoundException {
		if (!_hasDriverInstance) {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
		}
		_hasDriverInstance = true;
	}
	
	/**
	 * Zwraca polaczenie do bazy danych uzyskane przy pomocy przekazanych ustawien
	 * 
	 * @return database _connection
	 * @throws Exception jesli nie uda sie polaczyc z baza
	 */
	public static Connection getConnection(DbConfig config) throws SQLException {
		if (config == null) {
			throw new NullPointerException("You must specify connection settings");
		}
		
		_config = config;
		
		if (_connection == null || _connection.isClosed()) {
			try {
				getDriverInstance();
			} catch (Exception e) {
				throw new SQLException("Could not initialize JDBC MySQL driver.");
			}
			try {
				_connection = (Connection) DriverManager.getConnection(
						"jdbc:mysql://" + config.getHost() +
						"/" + config.getSchema() +
						"?user=" + config.getUserName() +
						"&password=" + config.getUserPassword()
				);
			} catch (Exception e) {
				_Log.info(e.getMessage());
				throw new SQLException("Could not connect to DB. " + e.getMessage());
			}
		}
		
		return _connection;
	}
	
	public static boolean hasConnection() {
		return _connection != null;
	}
	
	
}
